package com.ddf.controller;

import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.View;

import com.ddf.entity.User;

/**
 * 自定义一个视图解析器的步骤
 * 1. 实现View接口，重写getContentType和render方法
 * 2. 在SpringMVC配置文件中配置根据bean来确定视图的解析器，并且通过Order属性指定优先级高于默认解析器
 * 3. SpringMVC实现了一些常用的试图解析器，需要重写方法，例如Excel
 * @author ddf 2016年9月2日下午4:21:26
 *
 */
@Component
public class XmlViewDemo implements View {

	@Override
	public String getContentType() {
		return "application/xml";
	}

	@Override
	public void render(Map<String, ?> map, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if(map != null && map.size() > 0) {
			response.setContentType(this.getContentType());
			StringBuilder sbl = new StringBuilder();
			sbl.append("<Xml>");
			for(Entry<String, ?> m : map.entrySet()) {
				if(m.getValue() instanceof User) {
					User user = (User) m.getValue();
					sbl.append("<Person>");
					sbl.append("<userName>" + nullToBlankStr(user.getUserName())
							+"</userName>");
					sbl.append("<password>" + nullToBlankStr(user.getPassword())
							+"</password>");
					sbl.append("<sex>" + nullToBlankStr(user.getSex())
							+"</sex>");
					sbl.append("<email>" + nullToBlankStr(user.getEmail())
							+"</email>");
					sbl.append("</Person>");
				}
			}
			sbl.append("</Xml>");
			response.getWriter().write(sbl.toString());
		}
	}
	
	private static String nullToBlankStr(String str) {
		if(str == null) {
			return "";
		}
		return str;
	}

}
